//
//  ISSafetyLocalNotificationManager.m
//  iPhoneSafety
//
//  Created by dl on 2019/1/8.
//  Copyright © 2019 com.li.ding. All rights reserved.
//

#import "ISSafetyLocalNotificationManager.h"
#import <UserNotifications/UserNotifications.h>

@implementation ISSafetyLocalNotificationManager

NW_SINGLETON_INSTANCE_METHOD_IMPLEMENTATION

- (void) postLocalNotiWithStrategy:(ISSafetyAlarmStrategy)strategy {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (@available(iOS 10.0, *)) {
            [self postLocalNotiForIOS10WithStrategy:strategy];
        } else {
            [self postLocalNotiBeforeIOS10WithStrategy:strategy];
        }
    });
}

- (void) postLocalNotiBeforeIOS10WithStrategy:(ISSafetyAlarmStrategy)strategy {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.repeatInterval = 0;
    
    notification.alertTitle = @"警报";
    notification.alertBody =  [self localNotificationBodyWithStrategy:strategy];;
    notification.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    
    NSLog(@"Post Local Notification before iOS 10");
}

- (void) postLocalNotiForIOS10WithStrategy:(ISSafetyAlarmStrategy)strategy API_AVAILABLE(ios(10.0)) {
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = @"警报";
    content.body = [self localNotificationBodyWithStrategy:strategy];
    content.sound = [UNNotificationSound defaultSound];
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:1 repeats:NO];
    
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                          content:content trigger:trigger];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    }];
    
    NSLog(@"Post Local Notification after iOS 10");
}

- (NSString *) localNotificationBodyWithStrategy:(ISSafetyAlarmStrategy)strategy {
    return @{
             @(ISSafetyAlarmStrategyPocket): @"口袋模式触发警告",
             @(ISSafetyAlarmStrategyDesk): @"桌面模式触发警告",
             @(ISSafetyAlarmStrategyCharging): @"充电模式触发警告",
             @(ISSafetyAlarmStrategyAirplan): @"飞行模式触发警告",
             @(ISSafetyAlarmStrategyHeadset): @"耳机模式触发警告",
             }[@(strategy)];
}

@end
